package com.tanhua.dubbo.utils;

import com.tanhua.domain.mongo.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

/**
 * 获取最新的自增长id
 */
@Component
public class IdService {

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 获取某个表的最新ID
     * @return
     */
    public Long getNextId(String collName) {
        Query query = new Query(Criteria.where("collName").is(collName));

        Update update = new Update();
        update.inc("seqId", 1);

        // 如果没有数据满足条件，新增一条数据
        mongoTemplate.upsert(query, update, Sequence.class);

        // 获取更新后的数据
        Sequence sequence = mongoTemplate.findOne(query, Sequence.class);

        // 返回最新的id
        return sequence.getSeqId();

    }

}
